<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
    xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">

<head th:replace="main :: common_head">
    <style>
        .mylabel {
            display: inline;
        }

        .greenColor {
            color: green;
        }

        .redColor {
            color: red;
        }

        .changeI {
            display: block;
            width: 100%;
            height: 100%;
        }

        ul li {
            list-style: none;
            margin: 0;
            padding: 0;
        }

        .navbar .nav>li>.dropdown-menu::before {
            display: none !important;
        }

        .navbar .nav>li>.dropdown-menu::after {
            display: none !important;
        }

        .dropdown-menu:hover,
        .dropdown-menu:hover {
            display: none !important;
        }

        .dropdown-menu:hover::before,
        .dropdown-menu:hover::after {
            display: none !important;
        }

        #myli>ul:hover::before {
            display: none;
        }

        [v-cloak] {
            display: none;
        }
    </style>
</head>

<body>
    <div id="app">
        <!--删除提示模态框-->
        <div id="delcfmModel1" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
            aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <h4 class="modal-title" id="myModalLabel">提示</h4>
                    </div>
                    <div class="modal-body">是否要删除？</div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        <button type="button" class="btn btn-primary" v-on:click="deleteEventConfirm">确定</button>
                    </div>
                </div>
                <!-- /.modal-content -->
            </div>
            <!-- /.modal-dialog -->
        </div>
        <div class="container-fluid-full">
            <div class="row-fluid">
        <div class="show" v-if="isShow">
            <div id="content" class="span10" style="width: 100%;">
                <ul class="breadcrumb" th:if="${#request.getParameter('breadcrumb') == 'true'}">
                    <li>
                        <i class="fas fa-circle-notch"></i>
                        <a id="home" href="#" onclick="parent.location.reload()">主页</a>
                        <i class="icon-angle-right"></i>
                    </li>
                    <li><a href="#">策略库展示</a></li>
                </ul>
                <div class="row-fluid sortable">
                    <div class="box span12">
                        <div class="box-header" data-original-title>
                            <h2><i class="halflings-icon white user"></i><span class="break"></span>策略库展示</h2>
                            <div class="box-icon"></div>
                        </div>
                        <div class="box-content">
                            <!-- 下拉菜单开始-->
                            
                            <div class="container" style="margin-left: 0px">
                                <ul id="mytab" class="nav nav-pills nav-justified" style="margin-left: 0px">
                                    <li role="presentation" class="dropdown" id="myli" style="float: left;">
                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" th:unless="${graphId}" style="border:1px solid black">请选择图谱<span class="caret"></span></a>
                                        <div th:each="graph,graphStat:${graphInfoList}" class="dropdown">
                                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" th:if="${graphId == graph.graphId}" th:text="${graph.graphName}" style="padding:5px 12px; text-decoration:none; line-height: 32px; border:1px solid black; border-radius:5px">
                                                <span class="caret"></span></a>

                                        </div>
                                        <ul class="dropdown-menu">
                                            <li th:each="graph:${graphInfoList}">
                                                <!-- todo 添加点击事件 -->
                                                <a th:href="@{/relationshipCom/viewRelationshipCom/}+${graph.graphId}"  th:text="${graph.graphName}"></a>
                                            </li>
                                        </ul>
                                    </li>
                                        <li style="color: red;margin-top: 7px;margin-left: 7px;" th:if="${graphId==null}"> 若要添加组合策略，请先选择图谱!</li>
                                    <div class="container" style="margin-left: 20px; float: left; width: 100px"  th:each="graph,graphStat:${graphInfoList}">
                                        <!-- todo 添加点击事件 -->
                                        <a class="btn btn-primary" th:if="${graphId == graph.graphId}" th:id="${graphId}"  th:name="${graph.graphName}" v-on:click="addOrEditStrategy($event,'add')" ref>添加策略</a>
                                    </div>
                                </ul>
                            </div>
                            <!-- 下拉菜单结束-->
                            <table id="tableContainer" class="table table-striped table-bordered bootstrap-datatable datatable">
                                <thead>
                                <tr>
                                    <th data-field="stgyCode">组合策略ID</th>
                                    <th data-field="deviceFromName">源设备名</th>
                                    <th data-field="deviceToName">目标设备名</th>
                                    <!-- <th data-field="lossRate">损耗率</th>
                                    <th data-field="typeName">能源属性</th> -->
                                    <th data-field="graphName">所属图谱</th>
                                    <th data-field="workTime">开始时间</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr th:each="relationEdge:${relationshipComList}">
                                    <td th:text="${relationEdge.stgyCode}"></td>
                                    <td class="center">
                                        <span style="margin-right: 5px;" th:each="deviceFromName:${relationEdge.deviceFromName}" th:text="${deviceFromName }"></span>
                                    </td>
                                    <td class="center" th:text="${relationEdge.deviceToName}"></td>
                                    <!-- <td class="center" th:text="${relationEdge.lossRate[0]}"></td> -->
                                    <!-- <td class="center" th:text="${relationEdge.typeName[0]}"></td> -->
                                    <td class="center" th:text="${relationEdge.graphName[0]}"></td>
                                    <td class="center" th:text="${relationEdge.workTime}"></td>
                                    <td class="center">
                                        <!-- todo 添加点击事件 -->
                                        <a class="btn btn-info" title="修改" v-on:click="addOrEditStrategy($event,'edit')" th:id="${relationEdge.stgyCode}" th:name="${relationEdge.graphName[0]}" ref>
                                            修改
                                        </a>
                                        <a class="btn btn-danger" href="#" title="删除"
                                        v-on:click="deleteEvent($event)" th:id="${relationEdge.stgyCode}">删除</a>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        </div>
        </div>
        <div class="add" v-if="isAdd">
            <div class="container-fluid-full">
                <div class="row-fluid">
                    <div id="content" class="span10" style="width: 100%;">
                        <ul class="breadcrumb" th:if="${#request.getParameter('breadcrumb') == 'true'}">
                            <li>
                                <i class="fas fa-circle-notch"></i>
                                <a id="home" href="#" onclick="parent.location.reload()">主页</a>
                                <i class="icon-angle-right"></i>
                            </li>
                            <li><a href="#">{{graphName}}</a></li>
                        </ul>
                        <div class="row-fluid sortable">
                            <div class="box span12">
                                <div class="box-header" data-original-title>
                                    <h2><i class="halflings-icon white edit"></i><span class="break"></span>添加{{graphName}}中的组合策略</h2>
                                </div>
                                <div class="box-content">
                                            <div class="add-form-table">
                                                <!-- <div class="strary-code">
                                                    <label>策略ID:</label>
                                                    <input type="text" v-model="addEdgeData.strategyCode">
                                                </div> -->
                                                <div class="source-from-device">
                                                    <label>目标设备:</label>
                                                    <select name="deviceTo" v-model="addEdgeData.sourceToId" v-on:change="addOrEditDeviceChange('add')">
                                                        <option v-for="data in addEdgeData.sourceToData" :value="data.deviceId" name="deviceTo">{{data.deviceName}}</option>
                                                    </select>
                                                </div>
                                                <div class="source-to-device">
                                                    <label>源设备:</label>
                                                    <div>
                                                        <div v-for="device in addEdgeData.sourceFromData">
                                                            <label>{{device.deviceFromName}}</label>
                                                            <input type="checkbox" :value="device.deviceFrom" :name="device.deviceFromName"  v-model="addEdgeData.sourceFromIds">
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="work-time" style="width: 500px">
                                                    <span>工作时间:</span>
                                                    <input type="text" v-model="addEdgeData.workTime">
                                                    <label>(此为一天24小时制,23-7,7-14)</label>
                                                </div>
                                                <!-- <div class="lose-rate-time" style="display: none;">
                                                    <span>损失率:</span>
                                                    <input type="text" v-model="addEdgeData.lossRate">
                                                </div> -->
                                            </div>
                                            <div class="form-actions" style="margin: 20px -10px 0px -10px;">
                                                <button id="add" type="submit" class="btn btn-primary" v-on:click="toAddEdge('add')">提交</button>
                                                <button type="button" class="btn btn-primary" v-on:click="backToShow">返回</button>
                                            </div>
    
                                </div>
                            </div><!--/span-->
                        </div><!--/row-->
                    </div>
                </div>
            </div>
        </div>
        <div class="edit" v-if="isEdit">            
            <div class="container-fluid-full">
                <div class="row-fluid">
                    <!-- start: Content -->
                    <div id="content" class="span10" style="width: 100%;">
                        <ul class="breadcrumb" th:if="${#request.getParameter('breadcrumb') == 'true'}">
                            <li>
                                <i class="fas fa-circle-notch"></i>
                                <a id="home" href="#" onclick="parent.location.reload()">主页</a>
                                <i class="icon-angle-right"></i>
                            </li>
                            <li><a href="#">{{graphName}}</a></li>
                        </ul>
                        <div class="row-fluid sortable">
                            <div class="box span12">
                                <div class="box-header" data-original-title>
                                    <h2><i class="halflings-icon white edit"></i><span class="break"></span>修改{{graphName}}中的组合策略</h2>
                                </div>
                                <div class="box-content">
                                    <div class="add-form-table">
                                        <!-- <div class="strary-code">
                                            <label>策略ID:</label>
                                            <input type="text" v-model="editEdgeData.strategyCode">
                                        </div> -->
                                        <div class="source-from-device">
                                            <label>目标设备:</label>
                                            <select name="deviceTo" v-model="editEdgeData.sourceToId" v-on:change="addOrEditDeviceChange('edit')">
                                                <option v-for="data in editEdgeData.sourceToData" :value="data.deviceId" name="deviceTo">{{data.deviceName}}</option>
                                            </select>
                                        </div>
                                        <div class="source-to-device">
                                            <label>源设备:</label>
                                            <div>
                                                <div v-for="device in editEdgeData.sourceFromData">
                                                    <label>{{device.deviceFromName}}</label>
                                                    <input type="checkbox" :value="device.deviceFrom" :name="device.deviceFromName"  v-model="editEdgeData.sourceFromIds">
                                                </div>
                                            </div>
                                        </div>
                                        <div class="work-time" style="width: 500px">
                                            <label>工作时间:</label>
                                            <input type="text" v-model="editEdgeData.workTime" >
                                            <label>(此为一天24小时制,23-7,7-14)</label>
                                        </div>
                                        <div class="lose-rate-time" style="display: none;">
                                            <span>损失率:</span>
                                            <input type="text" v-model="editEdgeData.lossRate">
                                        </div>
                                    </div>
                                    <div class="form-actions" style="margin: 20px -10px 0px -10px;">
                                        <button id="add" type="submit" class="btn btn-primary" v-on:click="toAddEdge('edit')">提交</button>
                                        <button type="button" class="btn btn-primary" v-on:click="backToShow">返回</button>
                                    </div>

                        </div>
                            </div>
                            <!--/span-->
                        </div>
                        <!--/row-->
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

<div th:replace="main::common_js"></div>

<script th:inline="javascript" th:src="@{/js/vue.min.js}"></script>
<script th:inline="javascript" th:src="@{/js/tools.js}"></script>
<script th:inline="javascript">
    //<![CDATA[
    var vm = new Vue({
        el: '#app',
        created: function () {
            // 判断url中是否有图谱id，如果有说明选择过图谱，那么获取这个图谱下的所有可以用的设备(用于后面下拉框)
            if (isNumber(getPathParamAferSlashLast())) {
                this.graphId = getPathParamAferSlashLast()
                this.setDeviceFromAndEnergyProperty(getPathParamAferSlashLast())
            }
        },
        data: {
            isShow: true,
            isAdd: false,
            isEdit: false,
            graphName: "",
            graphId: '',
            toDelStrategyCode: '',
            relationship: {
                lossRate: '',
                id: ''
            },
            addEdgeData: {
                strategyCode: '',
                sourceFromData: [],
                sourceFromName: '',
                sourceFromIds: [],
                sourceToData: '',
                sourceToId: '',
                energyTypeData: '',
                energyTypeIds: [],
                lostRates: [],
                workTime: ''
            },
            editEdgeData: {
                strategyCode: '',
                sourceFromData: [],
                sourceFromName: '',
                sourceFromIds: [],
                sourceToData: '',
                sourceToId: '',
                energyTypeData: '',
                energyTypeIds: [],
                lostRates: [],
                workTime: '',
                initSourceToSourceFromIdsMap:{}
            },
            deviceToEnergyTypeLossRateMap: {},
        },
        methods: {
            deleteEvent: function (e) {
                $("#delcfmModel1").modal("show");
                this.toDelStrategyCode = e.currentTarget.getAttribute("id")
                console.log(e.currentTarget.getAttribute("id"))
            },
            deleteEventConfirm: function () {
                that = this
                console.log("deleteEventConfirm")
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/multipower/relationshipCom/deleteEdgeMulti?stgyCode=" + that.toDelStrategyCode,
                    success: function (data) {
                        console.log(data)
                        $("#delcfmModel1").modal("hide"); //模态框隐藏
                        location.reload();
                    },
                    error: function (data) {
                        console.log(data, "error")
                        $("#delcfmModel1").modal("hide"); //模态框隐藏
                        location.reload();
                    }
                })
            },
            backToShow: function () {
                location.reload()
            },
            addOrEditDeviceChange: function (model) {
                // 获取一个目标设备下的checkbox中的源设备信息
                let deviceId = ''
                that = this

                if (model == "add") {
                    deviceId = that.addEdgeData.sourceToId
                } else {
                    deviceId = that.editEdgeData.sourceToId
                    if (that.editEdgeData.initSourceToSourceFromIdsMap[deviceId] != undefined) {
                        that.$set(that.editEdgeData,"sourceFromIds",that.editEdgeData.initSourceToSourceFromIdsMap[deviceId]);
                    } else {
                        that.$set(that.editEdgeData,"sourceFromIds",[]);
                    }

                }
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    async: false,
                    url: "/multipower/relationshipCom/edgeAddMulti?deviceTo=" + deviceId + "&graphId=" + that.graphId,
                    success: function (data) {
                        // 清空 deviceToEnergyTypeLossRateMap
                        for (let k of Object.keys(that.deviceToEnergyTypeLossRateMap)) {
                            that.$delete(that.deviceToEnergyTypeLossRateMap, k);
                        }
                        // 生成源设备(deviceFrom)id - {能源类型以及损失率的map}。
                        for (idx in data) {
                            that.$set(that.deviceToEnergyTypeLossRateMap, data[idx].deviceFrom, { "typeid": data[idx].typeId, "lossRate": data[idx].lossRate });
                        }
                        console.log("here set data",data,model);
                        if (model == "add") {
                            that.$set(that.addEdgeData, "sourceFromData", data)
                        } else {
                            console.log("here set data",data);
                            that.$set(that.editEdgeData, "sourceFromData", data)
                        }

                    }
                })
                this.$forceUpdate()
            },

            addOrEditStrategy: function (e, model = "add") {
                // 现实add界面
                if (model == "add") {
                	this.graphName = e.currentTarget.getAttribute('name')
                    this.$forceUpdate()
                    this.isEdit = false
                    this.isAdd = true
                }
                // 现实edit界面
                if (model == "edit") {
                    this.graphName = e.currentTarget.getAttribute('name')
                    this.$forceUpdate()
                    this.isEdit = true
                    this.isAdd = false
                    
                    // 提前获取edit保存的数据
                    let strategyCode = e.currentTarget.getAttribute('id')
                    that = this
                    $.ajax({
                        type: "POST",
                        dataType: "json",
                        url: "/multipower/relationshipCom/edgeEditMulti?stgyCode=" + strategyCode,
                        success: function (data_raw) {
                            let data = data_raw[0]
                            that.graphId = data.graphId[0]
                            that.setDeviceFromAndEnergyProperty(that.graphId)
                            that.$set(that.editEdgeData, "strategyCode", strategyCode)
                            that.$set(that.editEdgeData, "sourceFromIds", data.deviceFrom)
                            that.$set(that.editEdgeData, "sourceToId", data.deviceTo)
                            // 保存默认的，用于切换下拉框时恢复
                            let obj = {}
                            obj[data.deviceTo] = data.deviceFrom
                            that.$set(that.editEdgeData,"initSourceToSourceFromIdsMap",obj)

                            that.$set(that.editEdgeData, "energyTypeIds", data.typeId)
                            that.$set(that.editEdgeData, "lossRates", data.lossRate)
                            that.$set(that.editEdgeData, "workTime", data.workTime)

                            that.addOrEditDeviceChange("edit")
                        }
                    })
                }
                // 隐藏当前显示界面
                this.isShow = false
                // 隐藏策略展示残留的表格插件加入信息
                $("#tableContainer_wrapper").hide()
            
                this.$forceUpdate();

            },
            verificationInputRules: function (data) {
                // if (!data.strategyCode) {
                //     window.parent.layerAlert('策略id不可以为空', {
                //         icon: 5,
                //         title: "提示"
                //     });
                //     return false;
                // }

                if (data.sourceFromIds.length < 2) {
                    window.parent.layerAlert('源设备不可以少于2', {
                        icon: 5,
                        title: "提示"
                    });
                    return false;
                }

                if (!data.sourceToId) {
                    window.parent.layerAlert('目标设备不可为空', {
                        icon: 5,
                        title: "提示"
                    });
                    return false;
                }

                if (!data.workTime || !checkWorkTime(data.workTime)) {
                    window.parent.layerAlert('工作时间不正确或未填写！', {
                        icon: 5,
                        title: "提示"
                    });
                    return false;
                }
                return true;
            },
            toAddEdge: function (model) {
                that = this
                let toAddData = ''
                if (model == "add") {
                    toAddData = this.addEdgeData
                } else {
                    toAddData = this.editEdgeData
                }
                toAddData.energyTypeIds_ = []
                toAddData.lostRates_ = []
                // 此处根据deviceToEnergyTypeLossRateMap，补全损耗率以及能源类型
                if (that.deviceToEnergyTypeLossRateMap && toAddData.sourceFromIds) {
                    for (idx in toAddData.sourceFromIds) {
                        toAddData.energyTypeIds_.push(
                            that.deviceToEnergyTypeLossRateMap[toAddData.sourceFromIds[idx]].typeid
                        )

                        toAddData.lostRates_.push(
                            that.deviceToEnergyTypeLossRateMap[toAddData.sourceFromIds[idx]].lossRate
                        )
                    }
                }

                if (!this.verificationInputRules(toAddData)) {
                    return
                }
                // 这里提交添加，第一个请求检测是否策略id重复
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    url: "/multipower/relationshipCom/viewStgyCode",
                    success: function (data) {
                        if (model == "add" && data.indexOf(toAddData.strategyCode) != -1) {
                            window.parent.layerAlert('策略id已经存在请换一个！', {
                                icon: 5,
                                title: "提示"
                            });
                        } else {
                            let data = {
                                stgyCode: toAddData.strategyCode,
                                worktime: toAddData.workTime,
                                relationships: []
                            }
                            for (idx in toAddData.sourceFromIds) {
                                data.relationships.push(
                                    {
                                        deviceTo: Number(toAddData.sourceToId),
                                        deviceFrom: Number(toAddData.sourceFromIds[idx]),
                                        lossRate: Number(toAddData.lostRates_[idx]),
                                        typeId: Number(toAddData.energyTypeIds_[idx]),
                                        graphId: Number(that.graphId),
                                        isShard: 1,
                                        relName: "test",
                                    }
                                )
                            }
                            $.ajax({
                                type: "POST",
                                dataType: "json",
                                contentType: "application/json",
                                url: "/multipower/relationshipCom/addEdgeMulti",
                                data: JSON.stringify(data),
                                success: function (data) {
                                    console.log(data.status)
                                    if (data.status == "添加成功") {
                                        location.reload()
                                    } else {
                                        window.parent.layerAlert(data.status, {
                                            icon: 5,
                                            title: "提示"
                                        });
                                    }
                                }
                            })
                        }
                    }
                })
            },
            setDeviceFromAndEnergyProperty: function (graphId) {
                // 获取当前图谱可以有的源设备。下拉框里头的值
                that = this
                $.ajax({
                    type: "POST",
                    dataType: "json",
                    async: false,
                    url: "/multipower/relationshipCom/getDeviceList?graphId=" + graphId,
                    success: function (data) {
                        that.$set(that.addEdgeData, "sourceToData", data.deviceList)
                        that.$set(that.editEdgeData, "sourceToData", data.deviceList)
                        that.$forceUpdate();
                    }
                })
            }
        }
    })
    //]]>

</script>


<script th:inline="javascript">
    breadcrumb()
    window.onload = function () {
    	parent.modifyTitle("组合策略管理")
    }
</script>

<script th:src="@{/js/detect-element-resize.js}"></script>
<script th:src="@{/js/iframe-resize.js}"></script>

</body>

</html>